package com.mars.common.utils;

import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Beans {
	
	public static <T, U> U mapper(final T source, final Class<U> destType) {
		if(source == null) return null;
		return Dozers.mapper.map(source, destType);
	}
	
	public static <T, U> List<U> mappers(final List<T> sources, final Class<U> destType) {
		final List<U> dest = Lists.newArrayList();
		for (T source : sources) {
			dest.add(Dozers.mapper.map(source, destType));
		}

		return dest;
	}
	

	public static void copyProperties(Object source, Object target) {
		BeanUtils.copyProperties(source, target);
	}
	
	/**
	 * 将属性从source->target复制, 忽略target的null的值的属性
	 * 
	 */
	public static void copyPropertiesIgnoreNull(Object source, Object target) {
		BeanUtils.copyProperties(source, target, getNullProperties(source));
	}

	/**
	 * 将为null的properties给找出来,然后返回出来
	 */
	private static String[] getNullProperties(Object src) {
		BeanWrapper srcBean = new BeanWrapperImpl(src);
		PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
		Set<String> emptyName = new HashSet<>();
		for (PropertyDescriptor p : pds) {
			Object srcValue = srcBean.getPropertyValue(p.getName());
			if (srcValue == null) {
				emptyName.add(p.getName());
			}
		}
		String[] result = new String[emptyName.size()];
		return emptyName.toArray(result);
	}

}
